package st.business.tepth.business.visitor.visitorwork.work;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import st.business.tepth.base.OnDataConvertListener;
import st.business.tepth.config.Url;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-06-05 16:31
 */

public class WorkModel implements WorkContract.Model {

    @Override
    public Disposable getClassificationList(int repairId, final OnDataConvertListener<List<MultipleItemEntity>> listener) {
        return RxRestClient.builder()
                .url(Url.GetClassifications)
                .params("repairId", repairId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(convertToList(response));
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        listener.error(code, msg);
                    }
                })
                .build()
                .post();
    }

    private List<MultipleItemEntity> convertToList(String response) {
        List<MultipleItemEntity> list = new ArrayList<>();
        JSONArray jsonArray = JSONObject.parseArray(response);
        if (jsonArray != null) {
            for (int i = 0, size = jsonArray.size(); i < size; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                list.add(MultipleItemEntity.builder().setField("name",
                        jsonObject.getString("name"))
                        .setField("checked", i == 0)
                        .setField("unSolveCount",jsonObject.getInteger("count"))
                        .setField("count", jsonObject.getInteger("count"))
                        .setField("finish", jsonObject.getInteger("finish"))
                        .setField("id", jsonObject.getInteger("repairTaskId"))
                        .build());
            }
        }

        return list;
    }
}
